<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>JavaScript-使用WeakMap创建对象的私有属性 | 顾伊凡</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="我们都知道JavaScript本身并没有共有、私有属性的概念，不过我们可以通过一些方式实现私有属性。WeakMap也是ES6里就有了，不过我曾一直不太了解它的应用场景，看到有文章说用它的应用场景之一是实现私有属性。怎么实现？为何要用它实现？关于用WeakMap实现私有属性的方式，本文会从它最原始的面貌看起，理解使用WeakMap的意义。 闭包-可行吗？提到“私有”的实现方式，我的第一反应就是闭包，">
<meta name="keywords" content="JavaScript,WeakMap,ES6">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript-使用WeakMap创建对象的私有属性">
<meta property="og:url" content="http://yoursite.com/2018/08/28/JavaScript-使用WeakMap创建私有属性/index.html">
<meta property="og:site_name" content="顾伊凡">
<meta property="og:description" content="我们都知道JavaScript本身并没有共有、私有属性的概念，不过我们可以通过一些方式实现私有属性。WeakMap也是ES6里就有了，不过我曾一直不太了解它的应用场景，看到有文章说用它的应用场景之一是实现私有属性。怎么实现？为何要用它实现？关于用WeakMap实现私有属性的方式，本文会从它最原始的面貌看起，理解使用WeakMap的意义。 闭包-可行吗？提到“私有”的实现方式，我的第一反应就是闭包，">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2018-09-14T03:46:30.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JavaScript-使用WeakMap创建对象的私有属性">
<meta name="twitter:description" content="我们都知道JavaScript本身并没有共有、私有属性的概念，不过我们可以通过一些方式实现私有属性。WeakMap也是ES6里就有了，不过我曾一直不太了解它的应用场景，看到有文章说用它的应用场景之一是实现私有属性。怎么实现？为何要用它实现？关于用WeakMap实现私有属性的方式，本文会从它最原始的面貌看起，理解使用WeakMap的意义。 闭包-可行吗？提到“私有”的实现方式，我的第一反应就是闭包，">
  
    <link rel="alternate" href="/atom.xml" title="顾伊凡" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/css/style.css">
</head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">顾伊凡</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-JavaScript-使用WeakMap创建私有属性" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2018/08/28/JavaScript-使用WeakMap创建私有属性/" class="article-date">
  <time datetime="2018-08-28T02:58:49.000Z" itemprop="datePublished">2018-08-28</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      JavaScript-使用WeakMap创建对象的私有属性
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <p>我们都知道JavaScript本身并没有共有、私有属性的概念，不过我们可以通过一些方式实现私有属性。<br>WeakMap也是ES6里就有了，不过我曾一直不太了解它的应用场景，看到有文章说用它的应用场景之一是实现私有属性。怎么实现？为何要用它实现？<br>关于用WeakMap实现私有属性的方式，本文会<strong>从它最原始的面貌看起，理解使用WeakMap的意义</strong>。</p>
<h2 id="闭包-可行吗？"><a href="#闭包-可行吗？" class="headerlink" title="闭包-可行吗？"></a>闭包-可行吗？</h2><p>提到“私有”的实现方式，我的第一反应就是闭包，似乎可行：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Person = (<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> name;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">n</span>) </span>&#123;</span><br><span class="line">      name = n;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  Person.prototype.getName = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> name;</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> Person;</span><br><span class="line">&#125;());</span><br></pre></td></tr></table></figure><br>这样我们只要</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> person1 = <span class="keyword">new</span> Person(<span class="string">'小明'</span>);</span><br></pre></td></tr></table></figure>  
<p>这样<code>person1</code>就有它的私有<code>name</code>属性了，外部无法直接访问或修改改属性。等等，似乎有什么问题，如果我们再实例化一次<code>Person</code>呢？<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> person1 = <span class="keyword">new</span> Person(<span class="string">'小明'</span>);</span><br><span class="line"><span class="keyword">let</span> person2 = <span class="keyword">new</span> Person(<span class="string">'大明'</span>);</span><br><span class="line"><span class="built_in">console</span>.log(person1.getName()); <span class="comment">// 大明</span></span><br></pre></td></tr></table></figure><br>小明变成了大明！<code>person1</code>的<code>name</code>属性被覆盖了，所以这种方式实现的私有属性，实际上是被所有实例共享的，如果需要每个实例单独拥有自己的私有属性，这种方法就不行了。</p>
<h2 id="改进"><a href="#改进" class="headerlink" title="改进"></a>改进</h2><p>为了让每个实例拥有自己的私有属性，相互之间不影响，我们可以引入一个id作为每个实例的唯一标识，这样就实现了真正的私有属性：<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Person = (<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> private = &#123;&#125;;</span><br><span class="line">  <span class="keyword">let</span> privateId = <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">this</span>._privateId = privateId++;</span><br><span class="line">    private[<span class="keyword">this</span>._privateId] = &#123;&#125;;</span><br><span class="line">    private[<span class="keyword">this</span>._privateId].name = name;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  Person.prototype.getName = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> private[<span class="keyword">this</span>._privateId].name;</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> Person;</span><br><span class="line">&#125;());</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> person1 = <span class="keyword">new</span> Person(<span class="string">'小明'</span>);</span><br><span class="line"><span class="keyword">let</span> person2 = <span class="keyword">new</span> Person(<span class="string">'大明'</span>);</span><br><span class="line"><span class="built_in">console</span>.log(person1.getName()); <span class="comment">// 小明</span></span><br></pre></td></tr></table></figure><br>不过这样仍然有隐患，实例化后我们还是能更改其<code>_privateId</code>属性的值，一旦它被更改，私有属性就获取不到了。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">person1._privateId = <span class="number">111</span>;</span><br><span class="line"><span class="built_in">console</span>.log(person1.getName()); <span class="comment">// 报错</span></span><br></pre></td></tr></table></figure>
<p>所以我们改为用<code>Object.defineProperty</code>方法申明<code>_private</code>属性，防止它被更改。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Object</span>.defineProperty(<span class="keyword">this</span>, <span class="string">'_privateId'</span>, &#123;</span><br><span class="line">  value: privateId++,</span><br><span class="line">  writable: <span class="literal">false</span>, <span class="comment">// 设为不可写，_privateId就不会被更改了（其实默认就是false）</span></span><br><span class="line">&#125;);</span><br><span class="line"><span class="keyword">this</span>._privateId = privateId++;</span><br><span class="line">private[<span class="keyword">this</span>._privateId] = &#123;&#125;;</span><br><span class="line">private[<span class="keyword">this</span>._privateId].name = name;</span><br></pre></td></tr></table></figure>
<p>至此，我们仅用es5的特性就实现了私有属性，而然该方法还有以下几个弊端：</p>
<ul>
<li>即便<code>Person</code>的某个实例对象被垃圾回收了，<code>private</code>对象里存储的它的全部私有属性依旧不会被回收，这会导致内存泄漏问题</li>
<li>每个实例对象多出了一个<code>_privateId</code>属性，而且该方法不够直观优雅</li>
</ul>
<h2 id="WeakMap了解一下？"><a href="#WeakMap了解一下？" class="headerlink" title="WeakMap了解一下？"></a>WeakMap了解一下？</h2><p>既然我们不想多造一个单独的<code>_privateId</code>属性去实现私有属性的存储，那还有什么值可以作为该实例对象的唯一标识呢？它的内存地址？可是js似乎不允许直接获取一个对象的地址。直接拿对象本身作为key可以吗？<br><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">private[<span class="keyword">this</span>] = &#123;&#125;;</span><br><span class="line">private[<span class="keyword">this</span>].name = name;</span><br></pre></td></tr></table></figure><br>这么写在语法上当然没问题，但实际上一个对象的key只能是字符串或Symbol，因而所有对象都会被转为同一段符串“[object Object]”（<code>private[this] = {}</code>实际上就是<code>private[‘[object Object]’] = {}</code>），所以这种方法当然不行。<br>而ES6的Map和WeakMap是可以将对象作为key的（WeakMap的key只能是对象）。那我们用WeakMap试一下？</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Person = (<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> private = <span class="keyword">new</span> <span class="built_in">WeakMap</span>();</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">    private.set(<span class="keyword">this</span>, &#123;&#125;);</span><br><span class="line">    private.get(<span class="keyword">this</span>).name = name;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  Person.prototype.getName = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="keyword">return</span> private.get(<span class="keyword">this</span>).name;</span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> Person;</span><br><span class="line">&#125;());</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> person1 = <span class="keyword">new</span> Person(<span class="string">'小明'</span>);</span><br><span class="line"><span class="keyword">let</span> person2 = <span class="keyword">new</span> Person(<span class="string">'大明'</span>);</span><br><span class="line"><span class="built_in">console</span>.log(person1.getName()); <span class="comment">// 小明</span></span><br></pre></td></tr></table></figure>
<p>现在代码看上去简单优雅了很多，我们不再需要额外的id去标识每个实例，那内存泄漏问题呢？这就是为何要用WeakMap而不是Map了，WeakMap对key对象仅有“弱引用”，当没有其它引用指向该key对象时，该对象即可被垃圾回收，WeakMap不会阻止回收。</p>
<p>其实用WeakMap实现私有属性本身是比较简单的，但了解其背后的原因和原理更加重要。</p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2018/08/28/JavaScript-使用WeakMap创建私有属性/" data-id="cjt066zfn0003e0z4wywbmvnt" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JavaScript-WeakMap-ES6/">JavaScript,WeakMap,ES6</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2018/08/31/彻底搞懂white-space、word-break、word-wrap/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          彻底搞懂white-space、word-break、word-wrap
        
      </div>
    </a>
  
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/HTTPS-SSL-TLS-加密-对称加密-非对称加密-数字证书-数字签名/">HTTPS,SSL,TLS,加密,对称加密,非对称加密,数字证书,数字签名</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/JavaScript-WeakMap-ES6/">JavaScript,WeakMap,ES6</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/css-white-space-word-break-word-wrap-html/">css,white-space,word-break,word-wrap,html</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/immutable-js-immutable-JavaScript-持久化数据结构-结构共享-Vector-Trie-Clojure/">immutable.js,immutable,JavaScript,持久化数据结构,结构共享,Vector Trie,Clojure</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/immutable-js-immutable-JavaScript-持久化数据结构-结构共享-bitmap-transient-hash冲突-Vector-Trie-Clojure/">immutable.js,immutable,JavaScript,持久化数据结构,结构共享,bitmap,transient,hash冲突,Vector Trie,Clojure</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/尾递归-尾调用-trampoline-递归-迭代/">尾递归,尾调用,trampoline,递归,迭代</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/tags/HTTPS-SSL-TLS-加密-对称加密-非对称加密-数字证书-数字签名/" style="font-size: 10px;">HTTPS,SSL,TLS,加密,对称加密,非对称加密,数字证书,数字签名</a> <a href="/tags/JavaScript-WeakMap-ES6/" style="font-size: 10px;">JavaScript,WeakMap,ES6</a> <a href="/tags/css-white-space-word-break-word-wrap-html/" style="font-size: 10px;">css,white-space,word-break,word-wrap,html</a> <a href="/tags/immutable-js-immutable-JavaScript-持久化数据结构-结构共享-Vector-Trie-Clojure/" style="font-size: 10px;">immutable.js,immutable,JavaScript,持久化数据结构,结构共享,Vector Trie,Clojure</a> <a href="/tags/immutable-js-immutable-JavaScript-持久化数据结构-结构共享-bitmap-transient-hash冲突-Vector-Trie-Clojure/" style="font-size: 10px;">immutable.js,immutable,JavaScript,持久化数据结构,结构共享,bitmap,transient,hash冲突,Vector Trie,Clojure</a> <a href="/tags/尾递归-尾调用-trampoline-递归-迭代/" style="font-size: 10px;">尾递归,尾调用,trampoline,递归,迭代</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/03/">March 2019</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/10/">October 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/09/">September 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/08/">August 2018</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2019/03/04/写了一个可以拦截ajax请求并修改返回结果的插件/">写了一个可以拦截ajax请求并修改返回结果的chrome插件</a>
          </li>
        
          <li>
            <a href="/2018/10/17/Javascript的尾递归及其优化/">Javascript的尾递归及其优化</a>
          </li>
        
          <li>
            <a href="/2018/09/19/深入探究immutable.js的实现机制（二）/">深入探究immutable.js的实现机制（二）</a>
          </li>
        
          <li>
            <a href="/2018/09/12/深入探究immutable.js的实现机制（一）/">深入探究immutable.js的实现机制（一）</a>
          </li>
        
          <li>
            <a href="/2018/09/04/彻底搞懂https的加密机制/">彻底搞懂HTTPS的加密机制</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2019 顾伊凡<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/script.js"></script>



  </div>
</body>
</html>